package com.sx.micowell.module.invite

import android.Manifest
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.example.mvvm.bar.TitleBar
import com.example.mvvm.base.ContainerActivity
import com.example.mvvm.base.action.TitleBarAction

import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.Tips
import com.example.mvvm.until.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.miloyu.modelnet.response.getUrl
import com.sx.micowell.BR
import com.sx.micowell.R
import com.sx.micowell.databinding.FragInviteFriendBinding
import com.sx.micowell.framework.app.MyFragment
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.model.InviteFriendModel
import com.sx.micowell.framework.tools.CutUtil
import com.sx.micowell.framework.tools.image.HWImageManager
import com.tbruyelle.rxpermissions2.RxPermissions
import com.uuzuche.lib_zxing.activity.CodeUtils


/**
 * @Author: YY
 * @Time: 2021/9/10
 * @Describe 邀请好友
 */
@Route(path = RoutePath.INVITE_FRIENDS)
class InviteFriendFragment : MyFragment<FragInviteFriendBinding, ContainerActivity>(), TitleBarAction {

    lateinit var viewModel: InviteFriendModel

    override fun initViewModel() {
        super.initViewModel()
        viewModel = getFragmentScopeViewModel(InviteFriendModel::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.frag_invite_friend, BR.viewModel, viewModel)
    }

    override fun initView() {
        // 设置状态栏字体颜色
        ImmersionBar.with(this).statusBarDarkFont(true)
            .fitsSystemWindows(true).init()
        binding.title.setOnTitleBarListener(this)
    }

    override fun initData() {

    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel.savePhotoEvent.observe(this, {
            LogUtils.d("savePhotoEvent")
            CutUtil.shotView(binding.layoutView)
        })

        viewModel.sharePhotoEvent.observe(this, {
            LogUtils.d("sharePhotoEvent")
            RxPermissions(myActivity).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe {
                    if(it){
                        shareQR(CutUtil.shotBitmap(binding.layoutView))
                    }else{
                        Tips.showStatus(myActivity,Toast.LENGTH_SHORT,Tips.WARNING,"请授权读写权限再进行操作")
                    }
                }

        })

        // 二维码
        viewModel.inviteDataEvent.observe(this) {
            convertBitmap(it.share)
            binding.textView2.text = it.name
            context?.let { it1 ->
                if (it.userPhoto != null) {
                    Glide.with(it1).load(it.userPhoto.getUrl()).into( binding.imageView2)
                }
            }

        }
    }

    override fun getTitleBar(): TitleBar {
        return binding.title
    }

    override fun onLeftClick(v: View?) {
        myActivity.finish()
    }

    /**
     * 转换二维码
     */
    private fun convertBitmap(bitmapStr: String) {
        val width = resources.getDimension(R.dimen.dp_70).toInt()
        val height = resources.getDimension(R.dimen.dp_70).toInt()
        val qrBitmap = CodeUtils.createImage(
            bitmapStr, width, height, null)
        if (qrBitmap != null) {
            binding.imgQrCode.setImageBitmap(qrBitmap)
        }
    }

    private fun shareQR(bitmap: Bitmap) {
        if (bitmap == null) {
            ToastUtils.showShort("图片加载缓慢，请再次重试！")
            return
        }
        //由文件得到uri  这个url 有可能返回空，修改为把后面两个参数写入名字
        val url: String = MediaStore.Images.Media.insertImage(
            this.context?.contentResolver, bitmap,
            "micowell", "micowell" + "_pic"
        )
        val imageUri = Uri.parse(url)
        val shareIntent = Intent()
        shareIntent.action = Intent.ACTION_SEND
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri)
        shareIntent.type = "image/*"
        startActivity(Intent.createChooser(shareIntent, "分享到"))
    }
}